package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.PayFlow;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.dto.AlipayNotifyDto;
import cn.itsource.ymcc.dto.NotifyDto;
import cn.itsource.ymcc.mapper.PayFlowMapper;
import cn.itsource.ymcc.service.IPayFlowService;
import cn.itsource.ymcc.service.IPayOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2021-10-10
 */
@Transactional
@Slf4j
@Service
public class PayFlowServiceImpl extends ServiceImpl<PayFlowMapper, PayFlow> implements IPayFlowService {

    @Autowired
    private PayFlowMapper payFlowMapper ;

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public PayFlow create(NotifyDto dto) {
        AlipayNotifyDto alipayNotifyDto = (AlipayNotifyDto) dto;
        PayFlow payFlow = new PayFlow();
        payFlow.setCode(alipayNotifyDto.getCode());
        payFlow.setMsg(alipayNotifyDto.getMsg());
        payFlow.setNotifyTime(new Date());
        payFlow.setOutTradeNo(alipayNotifyDto.getOut_trade_no());
        payFlow.setSubject(alipayNotifyDto.getSubject());
        payFlow.setTotalAmount(new BigDecimal(alipayNotifyDto.getTotal_amount()));
        payFlow.setTradeStatus(alipayNotifyDto.getTrade_status());
        payFlow.setPaySuccess(alipayNotifyDto.isTradeSuccess());
        payFlow.setPassbackParams(alipayNotifyDto.getPassback_params());

        AssertUtil.isTrue(insert(payFlow),"支付流水保存失败");

        //修改支付单状态
        PayOrder payOrder = payOrderService.selectByOrderNo(alipayNotifyDto.getOut_trade_no());
        payOrder.setPayStatus(alipayNotifyDto.isTradeSuccess()?BaseConstants.Pay.STATUS_SUCCESS:BaseConstants.Pay.STATUS_FAIL);
        AssertUtil.isTrue(payOrderService.updateById(payOrder),"支付流水保存失败");
        log.info("保存支付流水{}",payFlow);
        log.info("修改支付单状态{}",payOrder);
        return payFlow;
    }

    @Override
    public PayFlow selectByOutTradeNo(String outTradeNo) {
        return payFlowMapper.selectByOutTradeNo(outTradeNo);
    }
}
